package com.live.shop.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;

import com.live.shop.model.CommentModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;
import com.live.shop.view.ToastUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

public class KuaiShouService extends Service {
    public KuaiShouService() {
    }
    int ListIndex =0;
    UserDatabase userDb;
    UserModel userModel;
    int serviceStartId;
    Timer timer;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        serviceStartId = startId;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(userModel.getPcIp().isEmpty()){
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);
                }else{
                    try {
                        JSONObject json = new JSONObject();
                        json.put("last_index",ListIndex);
                        getAccount(userModel.getPcIp(),json.toString());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        };
        // 立即执行一次task，然后每隔10分钟执行一次task
        timer.schedule(task, 1000, 1000*1);
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        //取最后一个
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            JSONObject dataJson = json.getJSONObject("data");
                            String userName =  dataJson.getString("username");
                            String userCom =  dataJson.getString("send_text");
                            ListIndex =  dataJson.getInt("last_index");
                            CommentModel commentModel = new CommentModel();
                            commentModel.setCommentsUser(userName);
                            commentModel.setCommentsTxt(userCom);

                            Intent intent = new Intent("AccessibilityServiceComment");
                            intent.putExtra("model", commentModel);
                            intent.putExtra("userCom", userCom);
                            intent.putExtra("userName", userName);
                            intent.putExtra("type", 2);//类型 1用户进直播间 2评论
                            intent.putExtra("function_id", userModel.getFunctionId());
                            sendBroadcast(intent);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 2:
                    ToastUtils.Setinfo(getApplicationContext(),"请求异常",2);
                    stopSelf(serviceStartId);
                    break;
                case 3:
                    ToastUtils.Setinfo(getApplicationContext(),"请配置电脑IP",2);
                    stopSelf(serviceStartId);
                    break;
            }
        }
    };
    public void getAccount(String url,String json){
        OkHttpUtils.sendOkHttpJsonRequest(url, json,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = 2;
                message.obj = e.toString();
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseData = response.body().string();
                Message message = new Message();
                message.what = 1;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        });
    }
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        boolean iswork = GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.SuspendedWindowService");
        if(iswork) stopService(new Intent(getApplicationContext(), SuspendedWindowService.class));
    }
}